package com.igame.Service.impl;

import com.igame.Service.OrderService;
import com.igame.common.Result;
import com.igame.constant.OrderConstant;
import com.igame.dto.OrderDto;
import com.igame.entity.Order;
import com.igame.mapper.GoodsMapper;
import com.igame.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;

@Service
public class OrderImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsMapper goodsMapper;
    @Override
    @Transactional
    public Result addOrder(OrderDto orderDto) {
        try {
            for (Integer integer : orderDto.getGoodsId()) {
                Order order =new Order();
                Order exist = orderMapper.OrderExist(orderDto.getUserId(), integer);
                if (exist==null){
                    order.setUserId(orderDto.getUserId());
                    order.setGoodsId(integer);
                    order.setCreateTime(LocalDateTime.now());
                    order.setState(OrderConstant.obligation);
                    orderMapper.insert(order);
                }else {
                    throw new RuntimeException("订单已存在");
                }
            }
        } catch (Exception e) {
            // 发生异常时回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

    @Override
    @Transactional
    public Result updateState(OrderDto orderDto,Integer state) {

        try {
            for (Integer integer : orderDto.getGoodsId()) {
                Order order =new Order();
                if (state==1){
                    order.setState(OrderConstant.pendingReceipt);
                }else{
                    order.setState(OrderConstant.Completed);
                }
                order.setUserId(orderDto.getUserId());
                order.setGoodsId(integer);
                orderMapper.updateState(order);
            }
            for (int i = 0; i < orderDto.getGoodsId().size(); i++) {
                goodsMapper.setGoodsState(orderDto.getGoodsId().get(i),1);
            }
        } catch (Exception e) {
            // 发生异常时回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error(e.getMessage());
        }
        return Result.success();
    }
}
